interval = 0
time = 0
var pattern = /^.+@.+\..+$/i

var schoolID = {}
var IDSchool = {}

getContestInfo((data) => {
    tshirtSize = data.tshirt_size
    for(let i=0;i<tshirtSize.length;i++) {
        $("#size").append('<option value="' + tshirtSize[i] + '">' + tshirtSize[i] + '</option>')
    }
})

requestServer("/api/getIDSchool", "GET", defaultHeader.copy(), {}, data => {
    IDSchool = data
    for(let id in IDSchool) 
        $("#school").append("<option value='" + id + "'>" + IDSchool[id] + "</option>")
}, () => {})

$("#sendCaptcha").click(e => {
    if(!checkEmail()) {
        alert("邮箱格式有误")
        return;
    }
    $("#sendCaptcha").addClass("am-disabled")
    
    let mail = { email: $("#email")[0].value }
    if($("#stuid")[0].value != '') mail["stuid"] = $("#stuid")[0].value

    sendEmail(mail, "register", d => {
        time = 9
        $("#sendCaptcha").text("冷却：" + (time + 1) + "s")
        interval = setInterval(() => {
            if(time == 0) {
                $("#sendCaptcha").text("获取验证码")
                $("#sendCaptcha").removeClass("am-disabled")
                clearInterval(interval)
                return;
            }
            $("#sendCaptcha").text("冷却：" + time + "s")
            --time
        }, 1000)
    }, d => {
        $("#sendCaptcha").removeClass("am-disabled")
        alert("验证码发送失败\n" + d.msg)
    })
})

function checkEmail() {
    let val = $("#email")[0].value
    return pattern.test(val)
}

$("#btn-reg").click(e => {
    if($("#password")[0].value.length < 8) {
        alert("密码长度至少为 8 位")
        return;
    }
    if($("#password")[0].value != $("#cpassword")[0].value) {
        alert("两次输入的密码不同")
        return;
    }
    data = []
    data.push($("#name")[0].value)
    data.push($("#email")[0].value)
    data.push(parseInt($("#school")[0].value))
    data.push($("#stuid")[0].value)
    data.push($("#captcha")[0].value)
    data.push($("#size")[0].value)

    var hashSecret = CryptoJS.HmacSHA256($("#password")[0].value, keySecret);
    data.push(CryptoJS.enc.Hex.stringify(hashSecret))

    postRegister(data, e => {
        alert("注册成功，将开始登录")
        let loginData = {email: data[1], pwd_token: CryptoJS.enc.Hex.stringify(hashSecret)}
        postLogin(JSON.stringify(loginData), e => {
            alert("登录成功")
            localStorage.setItem("token", e)
            window.location.href = 'contest.html'
        }, e => {
            alert("登录失败\n" + e.msg)
        })
    }, e => alert(e.msg))
})

$("#stuid").on('input', e => {
    $("#email")[0].value = $("#stuid")[0].value + "@std.uestc.edu.cn"
})